using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

	public Transform checkpoint;
	public AudioSource checkSound;
	public AudioSource heartSource;
	public AudioClip killSound;
	public AudioClip footstepSound;
	public float finishRadius = 1f;
	public float speed = 1f;
	public float rotateSpeed = 0.5f;
	bool hitWall = false;
	bool inDanger = false;

	AudioMovement audioScript;
	AudioSource footstepsSource;

	// Use this for initialization
	void Start () {
		audioScript = GameObject.FindObjectOfType(typeof(AudioMovement)) as AudioMovement;
		footstepsSource = GetComponent<AudioSource>();
	}
	
	// Update is called once per frame
	void Update () {

		Vector3 deltaPos = new Vector3(0, 0, 0);

		if (audioScript.GetState() != AudioMovement.State.Dialog && audioScript.GetState() != AudioMovement.State.Victory)
		{
			if (Input.GetKey("w"))
				deltaPos.z +=  Time.deltaTime * speed;
			if (Input.GetKey("s"))
				deltaPos.z -= Time.deltaTime * speed;
		}
			if (Input.GetKey("a"))
				transform.Rotate(0, -rotateSpeed, 0);
			if (Input.GetKey("d"))
				transform.Rotate(0, rotateSpeed, 0);

		// Movement updates
		transform.Translate(deltaPos);
		Vector3 pos = transform.position;
		//Debug.Log(pos);

		pos.x = Mathf.Clamp(pos.x, -42.0f, 101.0f);
		pos.z = Mathf.Clamp(pos.z, -35.0f, 102.0f);
		transform.position = pos;

		// Check the movement sound
		if (deltaPos.magnitude > 0f)
		{
			if (!footstepsSource.isPlaying)
				footstepsSource.Play();
		}
		else 
			footstepsSource.Pause();

		// Move to next checkpoint
		if (Vector3.Distance(transform.position, checkpoint.position) < finishRadius && audioScript.GetState() == AudioMovement.State.Waiting)
			audioScript.ActivateNextCheckpoint();
	}

	public void Kill()
	{
		Application.LoadLevel("LostScene");
	}

	public void EnterDanger()
	{
		//footstepsSource.clip = heartSound;
		inDanger = true;
	}

	public void ExitDanger()
	{
		inDanger = false;
	}

	public bool isInDanger()
	{
		return inDanger;
	}

}
